<?php
/**
 * Created by PhpStorm.
 * User: asus
 * Date: 2017/2/26
 * Time: 13:47
 */

namespace Home\Controller;


use Home\Model\UserModel;
use Think\Controller;

class LoginController extends Controller
{
    public function index()
    {
        if(IS_POST){
            $data = i('post.');
            if(trim(empty($data['username'])) || trim(empty($data['password']))){
                $this->error('用户名或者密码为空');
            }
            $user = (new UserModel())->find();
            if($data['username'] == $user['user_name'] && md5($data['password'])==$user['user_password']){
                $_SESSION['admin']['user'] = $user['user_name'];
                $this->success('登陆成功',u('Index/index'));
            }else{
                $this->error('用户名或者密码错误');
            }
        }else {
            $this->display();
        }
    }

    public function changePW()
    {
        $data = i('post.');
        if(IS_POST){
            if(trim(empty($data['newpassword']))!=trim(empty($data['password']))){
                $this->error('两次输入密码不一致');
            }
            if($data['newpassword']==''||$data['password']==''){
                $this->error('新密码不能为空');
            }
            $old = (new UserModel())->find();
            if(md5($data['oldpassword'])!=$old['user_password']){
                $this->error('原密码输入错误');
            }
            $newdata = [
                'user_password'=>md5($data['password'])
            ];
            $res = (new UserModel())->where(['user_id'=>1])->save($newdata);
            if($res){
                session_unset();
                session_destroy();
                $this->success('修改成功，请重新登陆',u('Login/index'));
            }else{
                $this->error('修改失败');
            }
        }else {
            $this->display();
        }
    }
}